package com.ruoyi.dataserver.service.impl;

import com.ruoyi.dataserver.service.IFieldQueryService;
import com.ruoyi.dataserver.service.ISearchTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName intelligent-city
 * @Package com.lab.dataserver.service.impl
 * @ClassName FieldQueryServceImpl
 * @Description 字段查询实现类
 * @Company LAB
 * @Author LXK
 * @Date 2020/6/29 8:41
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Slf4j
@Component
public class FieldQueryServceImpl implements IFieldQueryService {
    @Autowired
    public JdbcTemplate jdbcTemplate;

    @Autowired
    public ISearchTableService tableService;

    @Override
    public Map<String, List> queryByLayerOrAuth(Map map) {

        List listLayer = (List) map.get("layerList");
        List listAuth = (List) map.get("fieldList");
        //过滤@之后的字符
        List list = new ArrayList();
        listLayer.forEach(lists -> {
            String tableString = tableService.searchLineTable(lists.toString().substring(0, lists.toString().indexOf("_")));
            list.add(tableString);
        });
        //分隔成字符串，然后拼成sql
        String field = String.join(",", listAuth);
        //获取所有查询集合
        List<Map<String,Object>> listSql = new ArrayList();
        list.forEach(lists -> {
            String sql = "SELECT " + field + " FROM \"" + lists + "\" GROUP BY " + field;
            listSql.addAll(jdbcTemplate.queryForList(sql));
        });
        //整理数据返回前台
        Map<String, List> listMap = new HashMap<>();
        listAuth.forEach(auth->{
            List listValue = new ArrayList();
            listSql.forEach(mapdata->{
                mapdata.forEach((k,v) ->{
                    if(k.equals(auth)){
                        listValue.add(listValue.size(),v);
                        List listValues = (List) listValue.stream().distinct().collect(Collectors.toList());
                        listMap.put(k,listValues);
                    }
                });
            });
        });
        return listMap;
    }
}
